package com.chen.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chen.common.Result;
import com.chen.pojo.Clock;
import com.chen.service.Impl.ClockServiceImpl;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author chen
 * @date 2022/6/11 15:50
 */
@RestController
@Api(value = "clockController", tags = "打卡")
@SuppressWarnings("all")
@RequestMapping("/clcok")
public class ClockController {

    @Autowired
    private ClockServiceImpl clockService;

    @PostMapping
    public Result<?> save(@RequestBody Clock clock) {
//判断是否已经打卡了
        if (clock.getId() == null) {
            String today = DateUtil.today();
            QueryWrapper<Clock> query = new QueryWrapper<>();
            query.eq("user", clock.getUser());
            query.eq("time", today);
            Clock one = clockService.getOne(query);
            if (one != null) {
                return Result.error(-1, "今天已经打过卡了");
            }
            clock.setTime(today);
        }
        clockService.saveOrUpdate(clock);
        return Result.success();
    }

    @GetMapping("/page")
    public IPage<Clock> findPage(@RequestParam Integer pageNum,
                                 @RequestParam Integer pageSize,
                                 @RequestParam(defaultValue = "") String user,
                                 @RequestParam(defaultValue = "") String location) {
        IPage<Clock> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Clock> queryWrqpper = new QueryWrapper<>();

        if (!"".equals(user)) {
            queryWrqpper.like("user", user);
        }
        if (!"".equals(location)) {
            queryWrqpper.like("location", location);
        }

        IPage<Clock> userPage = clockService.page(page, queryWrqpper);
        return userPage;

    }


    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable("id") Integer id) {
        return Result.success(clockService.removeById(id)) ;
    }

}
